import { createRouter, createWebHistory } from "vue-router";
import Home from '@/views/Home.vue'
import store from '@/store/index'
import storage from "@/utils/storage";
import { ElMessage } from "element-plus";


const routes = [
    {
        name: 'home',
        path: '/',
        meta: { title: '首页' },
        component: Home,
        redirect: 'welcome',
        children: [
            { name: 'welcome', path: '/welcome', meta: { title: '欢迎页' }, component: () => import('@/views/Welcome/Welcome.vue') },
            { name: 'Show', path: 'show', meta: { title: '数据看板', keep: true }, component: () => import('@/views/DataShow/DataShow.vue') },
            { name: 'users', path: 'users', meta: { title: '员工管理', keep: true }, component: () => import('@/views/Users.vue') },
            { name: 'mall', path: 'mall', meta: { title: '商品管理', keep: true }, component: () => import('@/views/Mall.vue') },
            { name: 'pages', path: 'page/:pageNum(\\d+)', meta: { title: '页面' }, component: () => import('@/views/Pages.vue') }
        ]
    },
    {
        name: 'login',
        path: '/login',
        meta: { title: '登录页面' },
        component: () => import('@/views/Login.vue')
    },
    {
        name: 'notfound',
        path: '/:pathMatch(.*)*',
        meta: { title: '页面未找到' },
        component: () => import('@/views/NotFound.vue')
    },

]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, form) => {
    // 用户信息鉴权
    if (to.path !== '/login') {
        if (!storage.getItem('userInfo')) {
            ElMessage.error('操作未经授权')
            return '/login'
        }
    }
    // 禁止重复登录
    if (to.path === '/login') {
        if (storage.getItem('userInfo')) {
            return '/'
        }
    }
})
export default router